<script setup>
import { upImgFun } from "@/utils";
import { toobarCfg } from './config.js'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { ref, onMounted, defineProps, watch, shallowRef, nextTick, defineEmits } from "vue";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

const emit = defineEmits(['changeValue']);
const toolbarConfig = ref(toobarCfg())
const editorConfig = { placeholder: '请输入内容...' }
const editorRef = shallowRef()
const mode = ref('default')
const value = ref('')
const props = defineProps({
  value: {
    type: String,
    default: '',
  },
  height: {
    type: String,
    default: '500px',
  },
});


const handleCreated = (editor) => {
  editorRef.value = Object.seal(editor) // 记录 editor 实例，重要！
  nextTick(() => {
    let imgMenuKeys = editor.getConfig().hoverbarKeys.image.menuKeys;
    imgMenuKeys.push("tailorImage");
    let uploadImageConfig = editor.getMenuConfig("uploadImage");
    uploadImageConfig.fieldName = "file";
    uploadImageConfig.customUpload = async (file, insertFn) => {
      const url = await upImgFun({ file });
      insertFn(url, file.name, url);
      uploadImageConfig.onBeforeUpload = function (data) {
        console.log(data);
      };
      uploadImageConfig.onSuccess = function (data) {
        console.log(data);
      };
    };
  })
}

watch(() => props.value, (newValue, oldValue) => {
  value.value = newValue
})
watch(() => value.value, (newValue) => {
  if (newValue !== '<p><br></p>') {
    emit('changeValue', newValue)
  } else {
    emit('changeValue', '')
  }
})
</script>

<template>
  <div style="border: 1px solid #ccc">
    <Toolbar class="bar" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
    <Editor class="editor" :style="{ height }" v-model="value" :defaultConfig="editorConfig" :mode="mode"
      @onCreated="handleCreated" />
  </div>
</template>

<style>
.bar {
  border-bottom: 1px solid #ccc
}

.editor {
  overflow: hidden;
}
</style>